# -*- coding: utf-8 -*-
import os

import requests
import sys


class Baidutieba(object):
    def __init__(self, tieba_name, pn):
        self.tieba_name = tieba_name
        self.base_url = 'https://tieba.baidu.com/f?kw={}&pn='.format(tieba_name)
        self.url_list = [self.base_url + str(i * 50) for i in range(pn)]
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def get_page(self, url):
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)
        _response = requests.get(url, headers=_user_agent)

        return _response.text

    def save_data(self, data, number):
        _filename = 'ext/E1_{0}_page{1}.html'.format(self.tieba_name, str(number + 1))
        with open(_filename, mode='w', encoding='utf-8')as f:
            f.write(data)

    def run(self):
        # 构建url列表
        # 构建请求头
        # 遍历url列表
        for _url in self.url_list:
            # 发起请求
            _data = self.get_page(_url)
            # 保存源码
            _number = self.url_list.index(_url)
            self.save_data(_data, _number)


def main():
    tieba_name = input('请输入贴吧名: ')
    pn = input('请输入最大页码: ')
    tieba = Baidutieba(tieba_name, int(pn))
    tieba.run()


if __name__ == '__main__':
    main()
